<?php


namespace App\Http\Controllers\Admin;


use App\Events\NoticeEvent;
use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\AdminTender;
use App\Models\Admin\AdminTenderSite;
use App\Models\Admin\Company;
use App\Models\Admin\Document;
use App\Models\Admin\DrugResidueProject;
use App\Models\Admin\DrugResidueTesting;
use App\Models\Admin\Menu;
use App\Models\Admin\User;
use App\Notifications\SiteNotice;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
//use DB;

class DocumentController extends AdminController
{
    use AdminTrait;

    use Notifiable;

    protected $model;
    protected $unique_id = '';
    public function __construct(Document $model)
    {
        parent::__construct();
        $this->model = $model;
    }
    /**
     * 定义验证规则
     * @var []
     */
    protected $validate_rule = [
        'title'=>'required',
        'first_menu_id'=>'required_if:document_type:1,2|integer',
        'sec_menu_id'=>'required_if:document_type:1,2|integer',
        'status'=>'required|in:0,1',
        'author'=>'required_unless:document_type,4',
        'type'=>'required|integer|exists:company_type,id',
        'document_type'=>'required|integer|min:1',
        'product_type'=>'required_if:document_type,1,2,3|integer|exists:admin_product,id',
        'version'=>'required_if:document_type,3',
    ];

    /**
     * 定特殊的验证规则
     */
    protected function rules()
    {
        return [
        ];
    }

    protected $err_msg = [
        'title.required'         => '标题不能为空',
        'author.required'         => '作者不能为空',
    ];

    protected function getField()
    {
        return ['id','type','first_menu_id','sec_menu_id','title','status','view_num','author','created_at','updated_at'];
    }
    protected function search($request){
        $select= $this->model->with(['companyType','menuFirst','menuSec','product']);
        ($type = $request->query('type')) && $select = $select->where('type',$type);
        ($document_type = $request->query('document_type')) && $select = $select->where('document_type',$document_type);
        ($product_type = $request->query('product_type')) && $select = $select->where('product_type',$product_type);
        $first_menu_id=$request->query('first_menu_id');
       if(isset($first_menu_id))
       {
           $select->where('first_menu_id',$first_menu_id);
       }
        ($sec_menu_id = $request->query('sec_menu_id')) && $select = $select->where('sec_menu_id',$sec_menu_id);
        ($title = $request->query('title')) && $select = $select->where('title','like','%'.$title.'%');
        ($author = $request->query('author')) && $select = $select->where('author','like','%'.$author.'%');
        !is_null(($status = $request->query('status'))) && $select = $select->where('status',$status);
        if ($create_at = $request->query('created_at')){
            $create_at_arr=explode(',',$create_at);
            if(count($create_at_arr)==2)
            {
                $time_1=$create_at_arr[0];
                $time_2=$create_at_arr[1];
                $where[]=['created_at','>=',$time_1];
                $where[]=['created_at','<',$time_2+86400];
                $select=$select->where($where);
            }
        }
//        dd($select);
        return $select;
    }

    protected function setRequestField($arr,$type=false){
        //过滤字段
        if(isset($arr['_token'])) unset($arr['_token']);
        if (isset($arr['sign'])) unset($arr['sign']);
        if (isset($arr['timeStamp'])) unset($arr['timeStamp']);
        return $arr;
    }

    protected function beforeIndex()
    {
        //获取类型
        $type_list=Menu::getMenuListAll();
        return ['company_menu_list'=>$type_list];
    }

    public function info(BaseRequest $request)
    {
        try {
            $input=$request->all();
            $rules=[
              'id'=>'required|integer|exists:document,id',
            ];
            $msg=[
              'id.exists'=>'该手册不存在！'
            ];
            $validator = Validator::make($input, $rules,$msg);
            if($validator->fails())
                return $this->error(['-1',$validator->errors()->first()]);
            $id=$input['id'];
            $info = $this->model->with(['companyType','menuFirst','menuSec','product'])->find($id);
            //获取类型
            $type_list=Menu::getMenuListAll();
            $data=[
              'info'=>  $info,
              'company_menu_list'=>  $type_list,
            ];

            return $this->success($data);
        }catch (\Exception $exception){
            return $this->error();
        }
    }

    public function baseData(BaseRequest $request)
    {
        $type_list=Menu::getMenuListAll();
        $data= ['company_menu_list'=>$type_list];
        return $this->success($data);
    }

    public function transformList($list)
    {
        $list->getCollection()->transform(function($item) {
            if($item->first_menu_id==0)
            {
                unset($item->menuFirst);
                unset($item->menuSec);
                $item->menu_first=[
                    'id'=>0,
                    'name'=>'首页'
                ];
                $item->menu_sec=[
                    'id'=>-1,
                    'name'=>''
                ];
            }
            return $item;
        });
        return $list;
    }

//    public function addSiteNotice(BaseRequest $request)
//    {
//

//    }

    public function addSiteNotice(BaseRequest $request)
    {
        isset($this->unique_id) && $this->unique_id = 0;

        if(true !== $msg = $this->validate_form($request)){
            //验证未通过
            return response()->json(['errcode'=>'40012','errmsg'=>$msg]);
        }

        //去除数组
        $data = $this->setRequestField($request->all());

        if (method_exists($this, 'otherData')) {
            $data=$this->otherData($data,$request->all());
        }

        DB::beginTransaction();
        try{
            //执行添加操作
            $result = $this->model->create($data);
            //站内通知
            $requestData=$request->all();
            if(isset($requestData['document_type']) && $requestData['document_type']==4 && !isset($requestData['id']))
            {
                //找出所有该类型的客户
                $company_type=$result->type;
                $companys=Company::where('model',$company_type)->get();
                //通知
                $notice=new SiteNotice($result);
                Notification::send($companys, $notice);
                //
//                $company_arr=$companys->toArray();
//                foreach ($company_arr as $k=>$v)
//                {
//                    $data=[
//                      'title'=>  $result->title,
//                      'content'=>  $result->content,
//                      'created_at'=>  $result->created_at,
//                    ];
//                    event(new NoticeEvent($v['id'],$data));
//                }

            }
            if (method_exists($this->model,'addLog')){
                $this->model->addLog($result,[],1);
            }
            DB::commit();
            return response()->json(['errcode'=>0,'errmsg'=>'ok']);
        }catch (\Exception $e){
            report($e);
            DB::rollBack();
            return $e->getMessage();
            return response()->json(['errcode'=>40006,'errmsg'=>'添加失败']);
        }
    }

    public function itemList(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $this->vali_rules['name']='string';
        $validator = Validator::make($input, $this->vali_rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $this->getPageAndSize($input);
        $list=DrugResidueProject::getList($input,$this->skip,$this->size);
        $count=DrugResidueProject::getCount($input);
        $data=[
            'list'=>$list,
            'count'=>$count,
        ];
        return  $this->success($data);
    }

    public function addItem(BaseRequest $request)
    {
        $input=$request->only('name');
        $rules=[
            'name'=>[
                'required',
                Rule::unique('drug_residue_project','name')
            ]
        ];
        $msg=[
            'name.unique'=>'名称已存在'
        ];
        $validator = Validator::make($input, $rules,$msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        DB::beginTransaction();
        try {
            $info=DrugResidueProject::create($input);
            DrugResidueProject::addLog($info->toArray(),[],1);
            DB::commit();
            return  $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    public function editItem(BaseRequest $request)
    {
        $input=$request->only('id','name');
        $rules=[
            'id'=>'bail|required|exists:drug_residue_project,id',
            'name'=>[
                'required',
                Rule::unique('drug_residue_project','name')->ignore($input['id']??0)
            ]
        ];
        $msg=[
            'name.unique'=>'名称已存在'
        ];
        $validator = Validator::make($input, $rules,$msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        DB::beginTransaction();
        try {
            $info=DrugResidueProject::find($id);
            $pre=$info->getOriginal();
            $info->name=$input['name'];
            $info->save();
            $next=$info->getChanges();
            DrugResidueProject::addLog($pre,$next,2);
            DB::commit();
            return  $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    public function deleteItem(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'id'=>[
                'required',
                Rule::exists('drug_residue_project','id')
            ],
        ];
        $validator = Validator::make($input,$rules ,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        //判断该项目是否被使用
        $is_bind=DrugResidueTesting::where('project_id',$id)->count();
        if($is_bind)
        {
            return  $this->error(['-1','项目已被使用，无法删除']);
        }
        DB::beginTransaction();
        try {
            $info=DrugResidueProject::find($id);
            $info->delete();
            DrugResidueProject::addLog($info->toArray(),[],3);
            DB::commit();
            return  $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return  $this->error();
        }
    }

    public function tenderList(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $validator = Validator::make($input, $this->vali_rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $this->getPageAndSize($input);
        $list=AdminTender::getList($input,$this->skip,$this->size);
        $count=AdminTender::getCount($input);
        $site_list=AdminTenderSite::pluck('name','id');
        $data=[
            'list'=>$list,
            'count'=>$count,
            'site_list'=>$site_list,
        ];
        return  $this->success($data);
    }

    public function deleteTender(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'id'=>[
                'required',
                Rule::exists('admin_tender','id')
            ],
        ];
        $validator = Validator::make($input,$rules ,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        //判断该项目是否被使用
        try {
            AdminTender::where('id',$id)->delete();
            return  $this->success();
        }
        catch (\Exception $exception)
        {
            return $this->error();
        }
    }
    public function changeTender(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'id'=>[
                'required',
                Rule::exists('admin_tender','id')
            ],
            'status'=>'required|in:0,1'
        ];
        $validator = Validator::make($input,$rules ,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        $status=$input['status'];
        //判断该项目是否被使用
        try {
            AdminTender::where('id',$id)->update(['status'=>$status]);
            return  $this->success();
        }
        catch (\Exception $exception)
        {
            return $this->error();
        }
    }

}
